$infile = $ARGV[0];
chomp($infile);
$outfile = $ARGV[1];
chomp($outfile);
$missfile = $ARGV[2];
chomp($missfile);
open TPED,"$infile.tped" or die "can't open $infile.tped\n";
open TFAM,"$infile.tfam" or die "can't open $infile.tfam\n";
open MISS,"$missfile" or die "can't open $missfile\n";
open(WRTFAM,">$outfile.tfam");
open(WRTPED,">$outfile.tped");
$num =0;
while($line = <MISS>)
{
	chomp($line);
	$tfamline = <TFAM>;
	chomp($tfamline);
	$tfam[$num] = $tfamline;
	@array = split(" ",$line);
	#print "$array[1]\t$array[3]\n";
	$arrmiss[$num] = $array[3];
	$num++;
}
while($line = <TPED>)
{
	chomp($line);
	@array = split(" ",$line);
	$num =0;
	$main = 0;
	for($i=4;$i<@array;$i++)
	{
		$snp1 = $array[$i];
		$i++;
		$snp2 = $array[$i];
		if(exists($hash{$tfam[$num]}))
		{
			
			$prev = $hash{$tfam[$num]};	
			#print $prev."\n";
			$present = $num;
			$prevsnp = $tped_final[$prev];
			$presentsnp = $snp1." ".$snp2;
			if($prevsnp eq "0 0")
			{
				$tped_final[$prev] = $presentsnp;
			}
			if($arrmiss[$present] < $arrmiss[$prev])
			{
				if($presentsnp ne "0 0")
				{
					$tped_final[$prev] = $snp1." ".$snp2;
				}
				$hash{$tfam[$prev]} = $present;
				$tfam_final[$prev]  = $tfam[$present]; 
			}
			
			
		}
		else
		{
			$tped_final[$main] = $snp1." ".$snp2;
			$tfam_final[$main] = $tfam[$num];
			$hash{$tfam[$num]} = $main;
			$main++;
		}	
		$num++;
	}
	$genotypes = join(" ",@tped_final);
	$hash_tped{$array[1]} = $array[0]." ".$array[1]." ".$array[2]." ".$array[3]." ".$genotypes ;
	for (keys %hash)
    	{
        	delete $hash{$_};
    	}
}
#print "$tfam_main_num\n";
for($i=0;$i<@tfam_final;$i++)
{
	print WRTFAM $tfam_final[$i]."\n";

}
while(($key,$value) = each %hash_tped)
{
	print WRTPED $value."\n";

}
